import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'
import { message } from 'ant-design-vue'
import { APP_CONFIG } from '@/config'

const service: AxiosInstance = axios.create({
  baseURL: APP_CONFIG.API_BASE_URL,
  timeout: APP_CONFIG.REQUEST_TIMEOUT,
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 添加token
    const token = JSON.parse(localStorage.getItem(APP_CONFIG.USER_INFO) || '{}')?.token || ''
    if (token) {
      config.headers.Authorization = `${token}`
    }
    // 图片服务替换url
    if (config.url?.includes('/image/upload')) {
      config.baseURL = APP_CONFIG.VITE_API_IMAGE_URL
    }
    // 文章模块替换url
    if (config.url?.includes('/article')) {
      config.baseURL = APP_CONFIG.VITE_API_ARTICLE_URL
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data
    if (res.code !== 200) {
      message.error(res.message || '请求失败')
      return Promise.reject(new Error(res.message || '请求失败'))
    }
    return res
  },
  (error) => {
    message.error(error.message || '网络错误')
    return Promise.reject(error)
  }
)

export default service
